<template>
  <base-content>
  <div class="q-pa-md">
  <q-form @submit="getStuAttendStat" class="flex q-gutter-md">
    <q-select
      name="preferred_genre"
      v-model="semesterPreferred"
      :options="semesterOption"
      :option-label="(item) => item === null ? null : item.semesterYear + ' ' + item.semesterType"
      :option-value="(item) => item === null ? null : item.semesterId"
      color="primary"
      filled
      clearable
      label="请选择学期"
      style="width: 300px;"
    />
    <q-btn icon="search" label="查询考勤数据" type="submit" color="primary"  />
  </q-form>
  <q-table
    :title="this.semesterPreferred.semesterYear+this.semesterPreferred.semesterType+' 考勤数据'"
    style="margin-top: 20px"
    :data="studentAttendTable.data"
    :columns="studentAttendTable.columns"
    :filter="studentAttendTable.filter"
    row-key="name"
    no-data-label="没有找到任何信息"
  >
    <template v-slot:top-right>
      <q-input dense debounce="300" v-model="studentAttendTable.filter" placeholder="Search">
        <template v-slot:append>
          <q-icon name="search"/>
        </template>
      </q-input>
      <q-btn
        color="primary"
        icon-right="archive"
        label="导出数据"
        no-caps
        @click="exportTable"
        style="margin-left: 20px"
      />
    </template>
    <template v-slot:body="props">
      <q-tr :props="props">
        <q-td :props="props" key="studentNumber">{{props.row.studentNumber}}</q-td>
        <q-td :props="props" key="studentRealName">{{props.row.studentRealName}}</q-td>
        <q-td :props="props" key="studentSex">{{props.row.studentSex}}</q-td>
        <q-td :props="props" key="collegeName">{{props.row.collegeName}}</q-td>
        <q-td :props="props" key="gradeId">{{props.row.gradeId}}</q-td>
        <q-td :props="props" key="majorName">{{props.row.majorName}}</q-td>
        <q-td :props="props" key="className">{{props.row.className}}</q-td>
        <q-td :props="props" key="semesterYear">{{props.row.semesterYear}}</q-td>
        <q-td :props="props" key="semesterType">{{props.row.semesterType}}</q-td>
        <q-td :props="props" key="statistics">{{props.row.statistics}}</q-td>
        <q-td :props="props" key="rank">{{props.row.rank}}</q-td>
        <q-td :props="props" key="operating">
          <q-btn label="查看详情" @click="detail(props.row.studentNumber)"/>
          <q-btn label="学生邮件" @click="confirmToStu(props.row.studentNumber,props.row.studentRealName,props.row.rank)" buttons label-ok="更改" label-cancel="取消"/>
          <q-btn label="家长邮件" @click="confirmToParent(props.row.studentNumber,props.row.studentRealName,props.row.rank)"/>
        </q-td>
      </q-tr>
    </template>
  </q-table>
  </div>
  </base-content>
</template>

<script>
import { exportFile } from 'quasar'
import BaseContent from '../../components/BaseContent/BaseContent'

function wrapCsvValue (val, formatFn) {
  // eslint-disable-next-line no-void
  let formatted = formatFn !== void 0 ? formatFn(val) : val
  // eslint-disable-next-line no-void
  formatted = formatted === void 0 || formatted === null ? '' : String(formatted)

  formatted = formatted.split('"').join('""')
  /**
     * Excel accepts \n and \r in strings, but some other CSV parsers do not
     * Uncomment the next two lines to escape new lines
     */
  // .split('\n').join('\\n')
  // .split('\r').join('\\r')

  return `"${formatted}"`
}
export default {
  name: 'AdminAttend',
  components: { BaseContent },
  data () {
    return {
      currentUserInfo: JSON.parse(sessionStorage.getItem('user_object')),
      semesterPreferred: { semesterId: '', semesterType: '', semesterYear: '' }, // 设置默认值为空
      semesterOption: [], // 这里是数据库返回的数据，数组里的对象用item标识
      filter: '',
      studentAttendTable: {
        filter: '',
        columns: [
          { name: 'studentNumber', label: '学号', align: 'left', field: 'studentNumber', sortable: true },
          { name: 'studentRealName', label: '姓名', align: 'left', field: 'studentRealName' },
          { name: 'studentSex', label: '性别', align: 'left', field: 'studentSex' },
          { name: 'gradeId', label: '年级', align: 'left', field: 'gradeId' },
          { name: 'collegeName', label: '学院', align: 'left', field: 'collegeName', sortable: true },
          { name: 'majorName', label: '专业', align: 'left', field: 'majorName', sortable: true },
          { name: 'className', label: '班级', align: 'left', field: 'className', sortable: true },
          { name: 'semesterYear', label: '学年', align: 'left', field: 'semesterYear', sortable: true },
          { name: 'semesterType', label: '学期', align: 'left', field: 'semesterType', sortable: true },
          { name: 'statistics', label: '旷课节数', align: 'left', field: 'statistics', sortable: true },
          { name: 'rank', label: '预警等级', align: 'left', field: 'rank', sortable: true },
          { name: 'operating', label: '操作', align: 'center', field: 'operating' }
        ],
        data: []
      }
    }
  },
  created () {
    this.getAllSemesterYear()
  },
  methods: {
    confirmToStu (e1, e2, e3) {
      const _e1 = e1
      const _e3 = e3
      this.$q.dialog({
        title: '邮件发送',
        message: '确认给' + e1 + ' ' + e2 + ' 发送考勤邮件吗?',
        cancel: '取消',
        persistent: true,
        ok: '确认发送'
      }).onOk(() => {
        const query = {
          url: '/MailSenderAttendServlet',
          methods: 'post',
          type: 'FORM',
          data: {
            userid: _e1,
            userType: 'student',
            attend: _e3
          }
        }
        this.$fetchData(query).then(res => {
          if (res.data.indexOf('未注册')) {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          } else {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          }
        }).catch(e => {
          console.log(e)
        })
      }).onCancel(() => {
        // console.log('>>>> Cancel')
      }).onDismiss(() => {
        // console.log('I am triggered on both OK and Cancel')
      })
    },
    confirmToParent (e1, e2, e3) {
      const _e1 = e1
      const _e3 = e3
      this.$q.dialog({
        title: '邮件发送',
        message: '确认给' + e1 + ' ' + e2 + ' 的家长发送考勤邮件吗?',
        cancel: '取消',
        persistent: true,
        ok: '确认发送'
      }).onOk(() => {
        const query = {
          url: '/MailSenderAttendServlet',
          methods: 'post',
          type: 'FORM',
          data: {
            userid: _e1,
            userType: 'parent',
            attend: _e3
          }
        }
        this.$fetchData(query).then(res => {
          if (res.data.indexOf('未注册')) {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          } else {
            this.$q.notify({
              icon: 'auto_graph',
              message: res.data,
              position: 'top',
              timeout: 1500,
              color: 'warming'
            })
          }
        }).catch(e => {
          console.log(e)
        })
      }).onCancel(() => {
        // console.log('>>>> Cancel')
      }).onDismiss(() => {
        // console.log('I am triggered on both OK and Cancel')
      })
    },
    exportTable () {
      // naive encoding to csv format
      const content = [this.studentAttendTable.columns.map(col => wrapCsvValue(col.label))].concat(
        this.studentAttendTable.data.map(row => this.studentAttendTable.columns.map(col => wrapCsvValue(
          typeof col.field === 'function'
            ? col.field(row)
            // eslint-disable-next-line no-void
            : row[col.field === void 0 ? col.name : col.field],
          col.format
        )).join(','))
      ).join('\r\n')

      const status = exportFile(
        this.semesterPreferred.semesterYear + this.semesterPreferred.semesterType + ' 考勤数据.csv',
        '\uFEFF' + content,
        'text/csv'
      )

      if (status !== true) {
        this.$q.notify({
          message: '导出文件失败...',
          color: 'negative',
          icon: 'warning'
        })
      }
    },
    // 查看学生考勤详情
    detail (e) {
      this.$router.push({
        path: '/AdminAttendDetail',
        query: {
          stuN: e
        }
      })
    },
    // 获取学期显示在下拉框
    getAllSemesterYear () {
      const queryYear = {
        url: '/getAllSemesterServlet',
        methods: 'get'
      }
      this.$fetchData(queryYear).then(res => {
        if (res.data !== null) {
          console.log(res)
          this.semesterPreferred = res.data[res.data.length - 1]// 绑定的默认数据为最新的学期
          this.semesterOption = res.data// 将获取到的学期数据返回下拉框的选择里
        } else {
          this.$q.notify({
            icon: 'announcement',
            message: '获取记录为空',
            color: 'red',
            position: 'top',
            timeout: 1500
          })
        }
      }).catch(e => {
        console.log(e)
      })
    },
    // 查询学生考勤数据
    getStuAttendStat () {
      const queryYear = {
        url: '/AdminAttendServlet',
        methods: 'get',
        params: {
          year: this.semesterPreferred.semesterYear,
          type: this.semesterPreferred.semesterType
        }
      }
      this.$fetchData(queryYear).then(res => {
        console.log(res)
        this.studentAttendTable.data = res.data
        const queryScoreRank = {
          url: '/AttendRankServlet',
          methods: 'get'
        }
        this.$fetchData(queryScoreRank).then(res => {
          console.log(res)// 获得了预警等级表的查询结果

          this.studentAttendTable.data.forEach((item, index) => {
            this.studentAttendTable.data[index].rank = '未到预警线'
            for (let i = 0; i < res.data.length; i++) { // 遍历预警等级表
              if (item.statistics >= res.data[i].warningStandardStart && item.statistics <= res.data[i].warningStandardEnd) { // 与标准进行比较
                this.studentAttendTable.data[index].rank = res.data[i].warningRank// 得出学生预警等级
                this.studentAttendTable.loading = !this.studentAttendTable.loading
              }
            }
          })
          this.studentAttendTable.loading = !this.studentAttendTable.loading
        }).catch(e => {
          console.log(e)
        })
      }).catch(e => {
        console.log(e)
      })
    }
  }

}
</script>

<style scoped>

</style>
